package com.qf.dao.impl;

import com.qf.dao.CartDao;
import com.qf.pojo.TbCart;
import com.qf.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/*
 *@Description:
 *@author:刘哥
 *@Date:86180 2022/8/17 17:28
 */
public class CartDaoImpl implements CartDao {
    private QueryRunner queryRunner=new QueryRunner(DataSourceUtils.getDataSource());
    @Override
    public List<TbCart> findById(Long id) {
        String sql="select * from tb_cart where id=?";
        try {
           return queryRunner.query(sql,new BeanListHandler<>(TbCart.class),id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public TbCart selectCart(Long id, Long pid) {


        String sql="select * from tb_cart where id=? and pid=?";
        try {
            return queryRunner.query(sql,new BeanHandler<>(TbCart.class),id,pid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int updateNum(Long id, Long pid, int num) {
        String sql="update tb_cart set num=num+? where id=? and pid=? ";
        try {
            return queryRunner.update(sql,num,id,pid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int insetCart(Long id, Long pid, int num) {
        String sql="insert into tb_cart (id,pid,num) values (?,?,?) ";
        try {
            return queryRunner.update(sql,id,pid,num);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteCart(Long id, long pid) {
        String sql="delete  from tb_cart where id=? and pid=? ";
        try {
             queryRunner.update(sql,id,pid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void clearCart(Long uid) {
        String sql="delete from tb_cart where id=?";
        try {
            queryRunner.update(sql,uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
